import Vue from 'vue'
import configdata from './config'
import store from '../store/index'

const app = new Vue({
	store,
});


const MyRequest = (url = '', method = 'GET', data = {}) => {
	let header = {'content-type': 'application/json'}
	if(app.$store.getters.hasLogin) {
		header = {'content-type': 'application/json', 'Authorization': 'Bearer ' + app.$store.getters.userInfo.token}
	} 
	
	url = configdata.HOST + url
	
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			method: method,
			data: data,
			header: header,
			success: res => {
				if(res.data.status === 0) {
					resolve(res.data.data)
				} else {
                    let msg = '';
					if (res.data.status === 400) {
                        for(let i in res.data.data) {
                            res.data.data[i].map((j) => {
                                msg += j + " ";
                            })
                        }
					} else {
                        if (res.data.status === 401) {
                           msg = '请登陆后在进行该操作';
                        } else {
                           msg = res.data.message || res.data.data || '发生错误';
						}
					}
                    uni.showToast({
                        title: msg,
                        icon:'none',
                    });
					reject('操作失败！');
				}
			},
			fail: () => {
                uni.showToast({
                    title: '网络错误，请稍后重试~',
                    icon:'none',
                    mask:true,
                });
				reject('请求失败！');
			},
			complete: () => {
			}
		});
	})
}

module.exports = {
	MyRequest
}